requirejs(['jquery', 'pageJs','config', 'arttemplateUtil','common','msg_util','echartsUtil','jquery_route','account','wdatePicker','validform'], function($, pageJs,config, arttemplateUtil,common,msg_util,echartsUtil,jquery_route,account) {
	var param = {}
	var searchuser_count;
	
	// 百分比计算
	var percentage=function (num, total) { 
	    return (Math.round(num / total * 10000) / 100.00 + "%");// 小数点后两位百分比
	   
	}
	var getData = function(){
		common.loading();
		var count;
		common.common_ajax_request('/api/seller/v1/queryUserList',param,false,function(data,code,msg){
			if(msg.businessCode==0){
				setData(data);
				pageJs.setPage(data.pageNo,data.totalPage,data.totalCount,callback);			
				searchuser_count=data.totalCount;
				// 统计功能
				common.common_ajax_request('/api/seller/v1/queryUserListStatistics',param,false,function(data,code,msg){
					if(code==200){
						$('#od_count').html(data.accountMoney);
						$('#serch_od_count').html(data.searchAccountMoney);
						$('#us_count').html(data.user_count);
						$('#serch_us_count').html(searchuser_count);
						$('#sub_od_percent').html(percentage(data.searchAccountMoney,data.accountMoney));
						$('#sub_us_percent').html(percentage(searchuser_count,data.user_count));
						//window.layer.msg(percentage(searchuser_count,data.user_count)+'  '+percentage(data.searchAccountMoney,data.accountMoney));
					}
				},"","post");
			}else{
				setData({});
				window.layer.msg("系统异常");
			}
			layer.closeAll('loading'); //关闭加载层
		},"","post");
	}
	var user_tpl;//订单列表模板
	var initTpl = function(){
		user_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/user_tpl.html'));
	}
	
	//订单列表
	var setData = function(data){
		var res = {
				records:data.records
		}
		$("#user_tpl").html(user_tpl(res));
	}
	
	var callback = function(page){
		param.pageNo=page
		getData();
	}
	
	var init = function() {
		initTpl();
		param.user_id=jquery_route.$urlparams['id'];
		getData();
		//统计全部用户服务反馈和不喜欢产品反馈次数
		queryAllEvaluateStyleCount();

	};
	//查询验证
	var validserchform = $("#serchForm").Validform({
		tiptype:4,
		postonce:true,
		isShowRight:false,
		datatype:{"numCompare":function(gets,obj,curform,regxp){
			var minnum = $.trim($("#serchForm input[name=first_order_num]").val());
			var maxnum = $.trim($("#serchForm input[name=last_order_num]").val());
			var reg = /^[1-9]\d{1,8}$|^[0-9]$/;
			if((minnum != "" && !reg.test(minnum)) || (maxnum != "" && !reg.test(maxnum))) {
				return "下单次数范围为[0-999999999]";
			}
			if(minnum != "" && maxnum != "") {
				if(parseInt(maxnum) < parseInt(minnum)) {
					return "开始下单次数必须小于结束下单次数";
				}
			}
			$("#serchForm input[name=first_order_num]").removeClass("Validform_error");
			$("#serchForm input[name=last_order_num]").removeClass("Validform_error");
			return true;
		}}
	});
	//查询
   $('.serchBtn').on('click',function(){
		param.user_id=undefined;
	   if(validserchform.check()){
		   param.pageNo=1;
		   $.each($('#serchForm').serializeArray(), function(i, item) {
				if(item.value==""){
					delete param[item.name]
				}else{
					param[item.name]=item.value;
				}
			})
			//param.msgflag = $("input[name=msgflag]").prop("checked");
			getData();
	   }
	});
	//重置
	$('.resetBtn').on('click',function(){
		param.user_id=undefined;
		$.each($('#serchForm').serializeArray(), function(i, item) {
			delete param[item.name];
		});
//		$("form[name=serchForm] input").val("");
		$("form[name=serchForm]")[0].reset()
		$("#serchForm input").removeClass("Validform_error");
		$("#serchForm .Validform_checktip").removeClass("Validform_wrong").html("");
		getData();
	});
	$('.excelBtn').on('click',function(){
		$("#excel").attr("action",config.apiRoot()+"/api/seller/v1/exportUserList");
		var html = [];
		$.each($('#serchForm').serializeArray(), function(i, item) {
			html.push("<input name=\""+item.name+"\" type='hidden' id=\""+item.name+"\" value=\""+item.value+"\" />");
		});
		$.each(config.setFullParameterArr({}), function(i, item) {
			html.push("<input name=\""+i+"\" type='hidden' id="+i+" value=\""+item+"\" />");
		});
		if(typeof param.user_id != 'undefined'){
			html.push("<input name=\"user_id\" type='hidden' value=\""+param.user_id+"\" />");
		}
		$("#excel").html(html.join(""));
		$("#excel").submit();
	});
	/*$("#serchForm input[name=first_register_time]").on('click',function(){
		var date_param = {el:'first_register_time'};
		
		if($("#serchForm input[name=last_register_time]").val() != undefined && $("#serchForm input[name=last_register_time]").val() !=""){
			date_param.maxDate=$("#serchForm input[name=last_register_time]").val();
		}
		WdatePicker(date_param);
	});
	$("#serchForm input[name=last_register_time]").on('click',function(){
		var date_param = {el:'last_register_time'};
		if($("#serchForm input[name=first_register_time]").val() != undefined && $("#serchForm input[name=first_register_time]").val() !=""){
			date_param.minDate=$("#serchForm input[name=first_register_time]").val();
		}
		WdatePicker(date_param);
	});
	$("#serchForm input[name=first_last_order_time]").on('click',function(){
		var date_param = {el:'first_last_order_time'};
		
		if($("#serchForm input[name=last_last_order_time]").val() != undefined && $("#serchForm input[name=last_last_order_time]").val() !=""){
			date_param.maxDate=$("#serchForm input[name=last_last_order_time]").val();
		}
		WdatePicker(date_param);
	});
	$("#serchForm input[name=last_last_order_time]").on('click',function(){
		var date_param = {el:'last_last_order_time'};
		if($("#serchForm input[name=first_last_order_time]").val() != undefined && $("#serchForm input[name=first_last_order_time]").val() !=""){
			date_param.minDate=$("#serchForm input[name=first_last_order_time]").val();
		}
		WdatePicker(date_param);
	});*/
	
	var upbalanceFrm;
	//修改账户余额
	$(document).off('click','.balanceLink').on('click','.balanceLink',function(){
		var userid=$(this).attr('data-id');
		$("#balanceModal input[name=userid]").val(userid);
		$("#balanceModal .staffName").html(account.userInfo.staffName);
		$("#balanceModal .staffNo").html(account.userInfo.staffNo);
		
		if(typeof upbalanceFrm =='undefined'){
			upbalanceFrm=$("#balanceModal form").Validform({
				tiptype:4,
				postonce:true,
				isShowRight:false
			});
		}
		upbalanceFrm.resetForm();
		upbalanceFrm.resetStatus();
		common.ajax_request2('get','/api/seller/v1/queryUserBalanceLog',{userid:userid},function($data,$code,$business){
			if($code==200){
				var _list_box=$('#balanceModal .list-body ul');
				_list_box.empty();
				$.each($data,function(index,data){
					if(index>=3){return false;}
					_list_box.append('<li><div class="list-id">账户余额：<span>'+data.after_period+'</span></div><div class="list-date">'+getLocalTime(data.add_time)+'</div><div class="list-name">操作人及工号：  '+data.staff_name+'   '+data.staff_no+'</div></li>');
				});
				$("#balanceModal").modal('show');
			}else{
				window.layer.msg($business.businessNote);
			}
		});
	});
	function getLocalTime(nS) {
//		return new Date(parseInt(nS) * 1).toLocaleString().substr(0,17);
//		return new Date(parseInt(nS) * 1).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
		return new Date(parseInt(nS) * 1).toLocaleString().replace(/:\d{1,2}$/,' ');
	} 
	$(document).off('click','.upbalance').on('click','.upbalance',function(){
		if(upbalanceFrm.check()){
			common.ajax_request2('post','/api/seller/v1/updateUserBalance',$("#balanceModal form").serializeArray(),function($data,$code,$business){
				if($code==200){
					window.layer.msg("修改成功");
					$("#balanceModal").modal('hide');
					getData();
				}else{
					window.layer.msg($business.businessNote);
				}
			});
		}
	});
	
	/*******************************************消息提示开始****************************************/
	
	//消息提示
	$(document).off('click','.mesInfo').on('click','.mesInfo',function(event){
		var $this = $(this);
		//获取用户id
		//var _userid=$(this).parent().find('span').html();
		//取消事件冒泡  
	    event.stopPropagation();  
	    msg_util.msgDialog(this,function(){
	    	//$this.hide();
	    	getData();
	    });
		
	});
	
	/*******************************************消息提示结束****************************************/
	
	
	/****************************************饼图创建开始*******************************************/
   /* var drawPie = function(title,dataJson)  
    {  
        var myChart = ec.init(document.getElementById('main'));  
        option = {
        		backgroundColor: '#fff', //设置背景色
        	    title : {
        	        text: title, //标题
        	        //subtext: '纯属虚构', //副标题
        	        x:'center' //居中
        	    },
        	    tooltip : {
        	        trigger: 'item',
        	        showDelay: 150,//显示延时，添加显示延时可以避免频繁切换
        	        padding: [5, 10, 20, 10],    //内边距
        	        hideDelay: 0,//隐藏延时
                    transitionDuration: 5,//动画变换时长
                    backgroundColor: 'rgba(0,0,0,0.7)',//背景颜色（此时为默认色）
        	        formatter: "{a} <br/>{b} : {c} ({d}%)"
        	    },
        	    legend: {
        	        orient: 'vertical',
        	        left: 'left',
        	        data: ['直接访问','邮件营销','联盟广告','视频广告','搜索引擎']
        	    },
        	    series : [
        	        {
        	            name: '',
        	            type: 'pie',
        	            radius : '65%', //图形比例大小
        	            center: ['50%', '50%'],
        	            data:dataJson, //数据源
        	            itemStyle: {
        	            	normal:{ 
                                 label:{ 
                                    show: true, 
                                    formatter: '{b} : {c} ({d}%)' 
                                 }, 
                                 labelLine :{show:true} 
                             }, 
        	                emphasis: {
        	                    shadowBlur: 10,
        	                    shadowOffsetX: 0,
        	                    shadowColor: 'rgba(0, 0, 0, 0.5)'
        	                }
        	            }
        	        }
        	    ]
        	};
        myChart.setOption(option);  
    }     */
    /****************************************饼图创建结束*******************************************/
    
    
    /****************************统计全部用户服务反馈和不喜欢产品反馈次数开始**********************************/
    
    var queryAllEvaluateStyleCount =function() {
    	common.common_ajax_request('/api/seller/v1/queryAllEvaluateStyleCount',
    			{}, false, function(data){
    		//设置全部用户服务反馈数		
    		$('#all_eval_count').html(data.allEvaluteCount);
    		//全部用户不喜欢产品反馈数
    		$('#not_all_like_eval_count').html(data.notAllLikeEvaluteCount);
		});
    }
    
    /****************************统计全部用户服务反馈和不喜欢产品反馈次数结束**********************************/
    
    
    /****************************点击全部用户服务反馈项占比图标弹出饼图开始***********************************/
	$('#all_eval_percent').on('click',function(event){
		
		
		common.common_ajax_request('/api/seller/v1/queryAllEvaluateStylePercent',{
			optionType:2
		}, false, function(data){
				
			if(data == "") {
				window.layer.msg("不存在全部用户服务反馈项占比信息");
				return;
			}
			$("#piewindown").modal('show');
			//data类型为：[{value:335, name:'直接访问'},{value:310, name:'邮件营销'},{value:234, name:'联盟广告'}]
			//drawPie('全部用户服务反馈项占比',data);
			echartsUtil.drawPie({title:'全部用户服务反馈项占比',dataJson:data});
		});
		
		
	});
	/****************************点击全部用户服务反馈项占比图标弹出饼图结束***********************************/
	
	
	/****************************点击全部用户不喜欢产品反馈项占比图标弹出饼图开始*******************************/
	$('#not_all_like_eval_percent').on('click',function(event){
		
		common.common_ajax_request('/api/seller/v1/queryAllEvaluateStylePercent',{
			optionType:1
		}, false, function(data){
				
			if(data == "") {
				window.layer.msg("不存在全部用户服务反馈项占比信息");
				return;
			}
			$("#piewindown").modal('show');
			//data类型为：[{value:335, name:'直接访问'},{value:310, name:'邮件营销'},{value:234, name:'联盟广告'}]
			//drawPie('全部用户不喜欢产品反馈项占比',data);
			echartsUtil.drawPie({title:'全部用户不喜欢产品反馈项占比',dataJson:data});
		});
		
		
	});
	
	/****************************点击全部用户服务反馈项占比图标弹出饼图结束***********************************/
    
   init();
});
